package com.coisshi.base.framework.handler;

import com.coisshi.base.common.exception.BizException;
import com.coisshi.base.framework.config.properties.MqttProperties;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@RequiredArgsConstructor
public class MqttMessageHandler implements MqttCallback {

    private final MqttClient mqttClient;
    private final MqttProperties mqttProperties;
    private final ApplicationEventPublisher eventPublisher;

    @PostConstruct
    public void init() throws BizException {
        try {
            mqttClient.setCallback(this);
            mqttClient.subscribe(mqttProperties.getDefaultTopic(), mqttProperties.getQos());
            log.info("已订阅MQTT主题: {}", mqttProperties.getDefaultTopic());
        } catch (MqttException e) {
            throw new BizException("MQTT订阅失败" + e.getMessage());
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
        String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
        log.info("接收到MQTT消息 - 主题: {}，内容: {}", topic, payload);
        // TODO: 业务处理、落库或推送

    }

    @Override
    public void connectionLost(Throwable cause) {
        log.error("MQTT连接丢失: {}", cause.getMessage());
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.debug("MQTT消息已成功发送");
    }
}

